﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using System.Collections;
using Lamex.Interface;
using Lamex.Common;
using Lamex.Library.CommonClass;
using DevExpress.XtraCharts;

namespace Lamex.mCapacity
{
    public partial class frmCAP_Owed_Analysis_Trending : frmBaseChild
    {
        string strD1, strD2;
        string strLevel, strSql;
        DataTable dt;

        public frmCAP_Owed_Analysis_Trending()
        {
            InitializeComponent();
        }

        private void frmCAP_Owed_Analysis_Trending_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            string CurUser = Lamex.Common.Loginer.CurrentUser.Account;

            dteStart.DateTime = DateTime.Now;

            gridView1.OptionsBehavior.Editable = false;
            gridView1.OptionsView.ColumnAutoWidth = true;

            doResetChildCbx();//重置子项控件

            //直接加载子项列表
            SetSubItemDataCollection("1=1", "SUB_FACTORY");
        }

        private void sbtnView_Click(object sender, EventArgs e)
        {
            gridView1.Columns.Clear();

            getFilterDate();//获取起止时间段
            getLevelString();//获取分析层级

            strSql = "";
            dt = null;

            getSQL_Trending();

            //刷新图表
            if (strSql != "")
            {
                dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(strSql);
                if (dt.Rows.Count > 0)
                {
                    setData_GridView(dt);
                    TotalSum();//统计求和

                    setData_ChartControl(dt, chartControl1, "计划生产日期", "数量");
                }
            }
        }

        //获取起止时间段
        private void getFilterDate()
        {
            strD1 = dteStart.Text.ToString();

            if (dteEnd.Text == "")
            {
                strD2 = strD1;
            }
            else
            {
                strD2 = dteEnd.Text.ToString();
            }
        }

        //获取分析层级字符串
        private string getLevelString()
        {
            strLevel = "";
            if (rbtnFactory.Checked == true)
            {
                strLevel = "分厂";
            }
            else if (rbtnStation.Checked == true)
            {
                strLevel = "工作站";
            }
            else if (rbtnProcess.Checked == true)
            {
                strLevel = "工作中心";
            }
            return strLevel;
        }

        //按趋势方式进行分析，即显示一段时间演化趋势
        private void getSQL_Trending()
        {
            if (cbxItems_Child.Text == "")
            {
                MessageBox.Show("请选择具体分析项目！");
                this.Text = "排产（欠货）趋势";
                return;
            }

            this.Text = cbxItems_Child.SelectedValue.ToString() + " " + getLevelString() + " 排产（欠货）趋势( " + strD1 + " - " + strD2 + " )";

            string strCurItem = cbxItems_Child.Text;

            if (rbtnFactory.Checked == true)
            {
                getSQL_Trending_By_Factory(strCurItem);
            }
            else if (rbtnStation.Checked == true)
            {
                getSQL_Trending_ByLevel("WORKSTATION", strCurItem);
            }
            else if (rbtnProcess.Checked == true)
            {
                getSQL_Trending_ByLevel("PROCESS_CODE", strCurItem);
            }
        }

        private void getSQL_Trending_By_Factory(string strCurItem)
        {
            strSql = @"SELECT a.Product_TS AS 计划生产日期,CAST(Package_QTY AS DECIMAL(18,2)) AS 数量,CAST(PROCESS_TIME/60 AS DECIMAL(18,2)) AS 标准工时
                        FROM
                        (SELECT Product_TS,SUM(PROCESS_TIME) AS PROCESS_TIME
                        FROM View_OP_Follow_Process_Time
                        WHERE Product_TS>='" + strD1 + @"' AND  Product_TS<='" + strD2 + @"' AND SUB_FACTORY='" + strCurItem + @"'
                        GROUP BY Product_TS) AS a
                        LEFT JOIN
                        (SELECT Product_TS,SUM(OWED_QTY) AS Package_QTY
                        FROM
                        (SELECT DISTINCT Product_TS,Package_Mo,OWED_QTY
                        FROM View_OP_Follow_Process_Time
                        WHERE Product_TS>='" + strD1 + @"' AND  Product_TS<='" + strD2 + @"' AND SUB_FACTORY='" + strCurItem + @"') AS b
                        GROUP BY Product_TS) AS c
                        ON a.Product_TS=c.Product_TS";
        }

        private void getSQL_Trending_ByLevel(string strLevelType, string strCurItem)
        {
            strSql = @"SELECT a.Product_TS AS 计划生产日期,CAST(Part_QTY AS DECIMAL(18,2)) AS 数量,CAST(PROCESS_TIME/60 AS DECIMAL(18,2)) AS 标准工时
                        FROM
                        (SELECT Product_TS,SUM(PROCESS_TIME) AS PROCESS_TIME
                        FROM View_OP_Follow_Process_Time
                        WHERE Product_TS>='" + strD1 + @"' AND  Product_TS<='" + strD2 + @"' AND " + strLevelType + @"='" + strCurItem + @"'
                        GROUP BY Product_TS) AS a
                        LEFT JOIN
                        (SELECT Product_TS,SUM(OWED_QTY*Part_QTY/Order_QTY) AS Part_QTY
                        FROM
                        (SELECT DISTINCT Product_TS,Package_Mo,Part_No,OWED_QTY,Part_QTY,Order_QTY
                        FROM View_OP_Follow_Process_Time
                        WHERE Product_TS>='" + strD1 + @"' AND  Product_TS<='" + strD2 + @"' AND " + strLevelType + @"='" + strCurItem + @"') AS b
                        GROUP BY Product_TS) AS c
                        ON a.Product_TS=c.Product_TS";
        }

        private void setData_GridView(DataTable dt)
        {
            if (dt.Rows.Count > 0)
            {
                gridControl1.DataSource = dt;
                //gridView1.OptionsBehavior.Editable = false;
                //gridView1.OptionsView.ColumnAutoWidth = true;

                //refreshPositionStaduss();
            }
        }

        private void setData_ChartControl(DataTable dt, ChartControl chart, string strFeild_Key, string strFeild_Value)
        {
            chart.Series.Clear();

            if (dt.Rows.Count != 0)
            {
                Series series1 = new Series("", ViewType.Line);

                foreach (DataRow dr in dt.Rows)
                {
                    SeriesPoint p = new SeriesPoint();

                    if (checkBox1.Checked == true)
                    {
                        //因处理不了SYSTEM.DBNull报错，已强制在SQL语句中已将DBNull转换为0
                        //原值显示
                        //防止NULL值报错
                        if (double.Parse(dr["标准工时"].ToString()) != 0)  //不能用NULL代替空
                        {
                            double[] d = new double[] { double.Parse(Math.Round((decimal.Parse(dr[strFeild_Value].ToString())), 2).ToString()) };
                            p.Values = d;
                            setPointArgument(dr, strFeild_Key, p);
                            series1.Points.Add(p);
                        }
                    }
                    //不过滤消除0值及NULL值
                    else
                    {
                        double[] d = new double[] { double.Parse(Math.Round((decimal.Parse(dr[strFeild_Value].ToString())), 2).ToString()) };
                        p.Values = d;
                        setPointArgument(dr, strFeild_Key, p);
                        series1.Points.Add(p);
                    }
                }

                chart.Series.Add(series1);
                chart.Legend.Visibility = DevExpress.Utils.DefaultBoolean.False;
                Legend Legends = (Legend)chart.Legend;
                Legends.Visibility = DevExpress.Utils.DefaultBoolean.True;
                Legends.AlignmentVertical = LegendAlignmentVertical.Top;
                Legends.AlignmentHorizontal = LegendAlignmentHorizontal.Left;
                Legends.TextVisible = true;

                //强制显示所有x轴标签
                XYDiagram diagram = ((XYDiagram)chart.Diagram);
                diagram.AxisX.QualitativeScaleOptions.AutoGrid = false;
                diagram.AxisX.Label.ResolveOverlappingOptions.AllowHide = false;

                //设置Series的标签
                series1.LabelsVisibility = DevExpress.Utils.DefaultBoolean.True;//每个点都显示数据
            }
        }

        //排除因IE_WorkCenter_Definition、OP_MGT_Factory_Workstation、OP_MGT_Workstation_Process三个表中
        //PROCESS_CODE、WORKSTATION未同步定义，导致x轴标签出现NULL值，Argument报错，
        public void setPointArgument(DataRow dr, string strFeild_Key, SeriesPoint p)
        {
            if (dr[strFeild_Key].ToString() == "")
            {
                p.Argument = "NULL";
            }
            else
            {
                p.Argument = dr[strFeild_Key].ToString();
            }
        }

        #region 选项区联动设置-查询条件初始化

        private void rbtnFactory_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnFactory.Checked == true)
            {
                doClearViewAndChartData();

                cbxItems_Father.Enabled = false;
                cbxItems_Child.Enabled = true;

                doResetChildCbx();

                //直接加载子项列表
                SetSubItemDataCollection("1=1", "SUB_FACTORY");
            }
        }

        private void rbtnStation_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnStation.Checked == true)
            {
                doClearViewAndChartData();

                cbxItems_Father.Enabled = true;
                cbxItems_Child.Enabled = true;

                doResetChildCbx();

                //待选择父项才加载子项列表
            }
        }

        private void rbtnProcess_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnProcess.Checked == true)
            {
                doClearViewAndChartData();

                cbxItems_Father.Enabled = true;
                cbxItems_Child.Enabled = true;

                doResetChildCbx();

                //待选择父项才加载子项列表
            }
        }

        private void cbxItems_Father_TextChanged(object sender, EventArgs e)
        {
            string strCondition = "";
            if (cbxItems_Father.Text.ToString() == "")
            {
                strCondition = "1=1";
            }
            else
            {
                strCondition = "SUB_FACTORY = '" + cbxItems_Father.Text.ToString() + "'";
            }

            //分厂不需要重置处理
            if (rbtnStation.Checked == true)
            {
                SetSubItemDataCollection(strCondition, "WORKSTATION");
            }
            else if (rbtnProcess.Checked == true)
            {
                SetSubItemDataCollection(strCondition, "PROCESS_CODE + '_' + PROCESS_NAME");
            }
        }

        //加载下拉选项
        private void SetSubItemDataCollection(string strCondition, string strLevel)
        {
            string sql = "";
            sql = @"SELECT DISTINCT " + strLevel + @" FROM View_OP_Resource_Plan
                    WHERE " + strCondition;
            DataTable dt = null;
            dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(sql);

            //额外加下拉选项
            ArrayList list = new ArrayList();
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(dr[0].ToString().Trim());
            }
            //list.Add("全部");
            cbxItems_Child.DataSource = list;
            cbxItems_Child.Text = "";
            //cbxSubItem.Text = "全部";
        }

        //重置子项控件
        private void doResetChildCbx()
        {
            cbxItems_Father.Text = "";
            cbxItems_Child.Text = "";

            cbxItems_Child.DataSource = null;
            cbxItems_Child.Items.Clear();
        }

        #endregion

        #region 选项区联动设置-查询时间初始化

        private void rbtnCurWeek_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnCurWeek.Checked == true)
            {
                doClearViewAndChartData();

                DateTime now = DateTime.Now;
                dteStart.DateTime = now.AddDays(-(int)now.DayOfWeek + 1);
                dteEnd.DateTime = now.AddDays(7 - (int)now.DayOfWeek);
            }
        }

        private void rbtnCurMonth_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnCurMonth.Checked == true)
            {
                doClearViewAndChartData();

                DateTime now = DateTime.Now;
                dteStart.DateTime = now.AddDays(-now.Day + 1);
                dteEnd.DateTime = now.AddMonths(1).AddDays(-now.AddMonths(1).Day + 1).AddDays(-1);
            }
        }

        private void rbtnCurSeason_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnCurSeason.Checked == true)
            {
                doClearViewAndChartData();

                DateTime now = DateTime.Now;
                var time = now.AddMonths(0 - ((now.Month - 1) % 3));
                dteStart.DateTime = time.AddDays(-time.Day + 1);
                var time1 = now.AddMonths((3 - ((now.Month - 1) % 3) - 1));
                dteEnd.DateTime = time1.AddMonths(1).AddDays(-time1.AddMonths(1).Day + 1).AddDays(-1);
            }
        }

        #endregion

        //重置图表
        private void doClearViewAndChartData()
        {
            gridView1.Columns.Clear();
            chartControl1.Series.Clear();
            chartControl2.Series.Clear();
            this.Text = "排产（欠货）趋势";
        }

        #region 选项区显示/隐藏、表数据导出/打印、表复制设置、表页脚设置、基础配置窗体跳转

        private void 隐藏选项区ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelTop.Height = 3;
        }

        private void 显示选项区ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelTop.Height = 84;
        }

        private void 导出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Lamex.Common.ExecelHelper.GridViewToExcel(gridView1);
        }

        private void 打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Lamex.Common.ExecelHelper.GridViewToPrint(gridControl1, this.Text);
        }

        //gridView仅复制单元格内容，复制选中行焦点单元格的值
        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control & e.KeyCode == Keys.C)
            {
                Clipboard.SetDataObject(gridView1.GetFocusedRowCellValue(gridView1.FocusedColumn));
                e.Handled = true;
            }

            //或设置属性
            //optionBehavior - CopyToClipboardWithColumnHeader = false;
            //optionSelection - MultiSelectMode = CellSelect;
        }

        //GRIDVIEW页脚汇总设置
        private void TotalSum()
        {
            gridView1.Columns[0].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
            gridView1.Columns[0].SummaryItem.DisplayFormat = "合计：";
            if (gridView1.Columns.Contains(gridView1.Columns[1]))
            {
                gridView1.Columns[1].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                this.gridView1.Columns[1].SummaryItem.DisplayFormat = "{0:N}";
                // this.gridView1.Columns[1].Width = 80;
            }
            if (gridView1.Columns.Contains(gridView1.Columns[2]))
            {
                gridView1.Columns[2].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                this.gridView1.Columns[2].SummaryItem.DisplayFormat = "{0:N}";
                //this.gridView1.Columns[2].Width = 80;
            }
        }

        //基础配置窗体跳转
        private void labelGoto_Click(object sender, EventArgs e)
        {
            Loginer.CurrentUser.FunctionId = "menuSCH_Owed_QTY_List";
            MdiTools.OpenChildWebBrowse(this.MdiParent as IMdiForm, new frmBaseChildWinForm("View_OP_Follow_Owed_QTY", 1, false, false), sender as ToolStripMenuItem);
        }

        #endregion

        #region 实例化标准功能

        public override void DoView(IButtonInfo sender)
        {
            sbtnView_Click(null, null);
            base.DoView(sender);
        }

        public override void DoExport(IButtonInfo sender)
        {
            导出ToolStripMenuItem_Click(null, null);
            base.DoExport(sender);
        }

        public override void DoPrint(IButtonInfo sender)
        {
            打印ToolStripMenuItem_Click(null, null);
            base.DoPrint(sender);
        }

        #endregion
    }
}